<template>
  <div class="merchant-analysis">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>商家运营分析</span>
          <div class="header-right">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :shortcuts="dateShortcuts"
              @change="handleDateChange"
            />
            <el-button type="primary" @click="handleExport">
              <i class="fas fa-download"></i> 导出报表
            </el-button>
          </div>
        </div>
      </template>

      <!-- 数据概览 -->
      <el-row :gutter="20" class="data-overview">
        <el-col :span="6" v-for="(item, index) in overviewData" :key="index">
          <el-card class="overview-card" shadow="hover">
            <div class="overview-content">
              <div
                class="overview-icon"
                :style="{ backgroundColor: item.color }"
              >
                <i :class="item.icon"></i>
              </div>
              <div class="overview-info">
                <div class="label">{{ item.label }}</div>
                <div class="value">{{ item.value }}</div>
                <div class="trend" :class="item.trend > 0 ? 'up' : 'down'">
                  {{ item.trend > 0 ? "+" : "" }}{{ item.trend }}%
                  <i
                    :class="
                      item.trend > 0 ? 'fas fa-arrow-up' : 'fas fa-arrow-down'
                    "
                  ></i>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 图表区域 -->
      <el-row :gutter="20" class="chart-row">
        <el-col :span="12">
          <el-card class="chart-card" shadow="hover">
            <template #header>
              <div class="chart-header">
                <span>交易趋势</span>
                <el-radio-group v-model="transactionChartType" size="small">
                  <el-radio-button label="amount">交易金额</el-radio-button>
                  <el-radio-button label="count">交易笔数</el-radio-button>
                </el-radio-group>
              </div>
            </template>
            <div class="chart-container">
              <div
                ref="transactionChart"
                style="width: 100%; height: 300px"
              ></div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card class="chart-card" shadow="hover">
            <template #header>
              <div class="chart-header">
                <span>商家分布</span>
                <el-radio-group v-model="distributionChartType" size="small">
                  <el-radio-button label="type">类型分布</el-radio-button>
                  <el-radio-button label="area">区域分布</el-radio-button>
                </el-radio-group>
              </div>
            </template>
            <div class="chart-container">
              <div
                ref="distributionChart"
                style="width: 100%; height: 300px"
              ></div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="20" class="chart-row">
        <el-col :span="12">
          <el-card class="chart-card" shadow="hover">
            <template #header>
              <div class="chart-header">
                <span>评分分布</span>
                <el-select
                  v-model="ratingDimension"
                  size="small"
                  style="width: 120px"
                >
                  <el-option label="综合评分" value="overall" />
                  <el-option label="服务质量" value="service" />
                  <el-option label="商品质量" value="product" />
                  <el-option label="环境卫生" value="environment" />
                  <el-option label="价格水平" value="price" />
                </el-select>
              </div>
            </template>
            <div class="chart-container">
              <div ref="ratingChart" style="width: 100%; height: 300px"></div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card class="chart-card" shadow="hover">
            <template #header>
              <div class="chart-header">
                <span>投诉分析</span>
                <el-radio-group v-model="complaintChartType" size="small">
                  <el-radio-button label="type">类型分布</el-radio-button>
                  <el-radio-button label="trend">趋势分析</el-radio-button>
                </el-radio-group>
              </div>
            </template>
            <div class="chart-container">
              <div
                ref="complaintChart"
                style="width: 100%; height: 300px"
              ></div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 商家排行 -->
      <el-card class="ranking-card" shadow="hover">
        <template #header>
          <div class="ranking-header">
            <span>商家排行</span>
            <el-radio-group v-model="rankingType" size="small">
              <el-radio-button label="revenue">营收排行</el-radio-button>
              <el-radio-button label="rating">评分排行</el-radio-button>
              <el-radio-button label="orders">订单排行</el-radio-button>
            </el-radio-group>
          </div>
        </template>
        <el-table :data="rankingList" border style="width: 100%">
          <el-table-column type="index" label="排名" width="80" />
          <el-table-column prop="name" label="商家名称" min-width="200" />
          <el-table-column prop="type" label="商家类型" width="100">
            <template #default="scope">
              <el-tag :type="getMerchantTypeTag(scope.row.type)">
                {{ getMerchantTypeLabel(scope.row.type) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            :prop="getRankingColumn"
            :label="getRankingLabel"
            width="150"
          >
            <template #default="scope">
              <span v-if="rankingType === 'revenue'"
                >¥{{ scope.row.revenue }}</span
              >
              <el-rate
                v-else-if="rankingType === 'rating'"
                v-model="scope.row.rating"
                disabled
                show-score
              />
              <span v-else>{{ scope.row.orders }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="trend" label="环比" width="100">
            <template #default="scope">
              <span :class="scope.row.trend > 0 ? 'trend-up' : 'trend-down'">
                {{ scope.row.trend > 0 ? "+" : "" }}{{ scope.row.trend }}%
              </span>
            </template>
          </el-table-column>
          
          <template #empty>
            <div class="empty-state">
              <el-empty 
                description="暂无排行数据" 
                :image-size="200"
              >
                <div class="empty-text">暂无商家排行数据</div>
                <div class="empty-subtext">商家有交易数据后将在此处显示</div>
              </el-empty>
            </div>
          </template>
        </el-table>
      </el-card>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch, onUnmounted } from "vue";
import { ElMessage } from "element-plus";
import * as echarts from "echarts";
import service from "@/api/axios";
import * as XLSX from "xlsx";

// 日期选择
const dateRange = ref([]);
const dateShortcuts = [
  {
    text: "最近一周",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      return [start, end];
    },
  },
  {
    text: "最近一月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      return [start, end];
    },
  },
  {
    text: "最近三月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
      return [start, end];
    },
  },
];

// 测试数据 - 数据概览
const testOverviewData = [
  {
    label: "总交易额",
    value: "¥1,234,567",
    trend: 12.5,
    icon: "fas fa-yen-sign",
    color: "#409eff",
  },
  {
    label: "总订单数",
    value: "8,234",
    trend: 8.3,
    icon: "fas fa-shopping-cart",
    color: "#67c23a",
  },
  {
    label: "活跃商家",
    value: "326",
    trend: -2.1,
    icon: "fas fa-store",
    color: "#e6a23c",
  },
  {
    label: "新增商家",
    value: "45",
    trend: 15.8,
    icon: "fas fa-user-plus",
    color: "#f56c6c",
  },
];

// 数据概览
const overviewData = ref(testOverviewData);

// 图表相关
const transactionChart = ref(null);
const distributionChart = ref(null);
const ratingChart = ref(null);
const complaintChart = ref(null);
const transactionChartType = ref("amount");
const distributionChartType = ref("type");
const ratingDimension = ref("overall");
const complaintChartType = ref("type");
const complaintChartInstance = ref(null);

// 排行相关
const rankingType = ref("revenue");
const rankingList = ref([]);

// 加载状态
const loading = ref(false);

// 测试数据 - 排行榜
const testRankingData = {
  revenue: [
    { name: "桂林景区", type: "scenic", revenue: 256800, trend: 12.3 },
    { name: "龙胜酒店", type: "hotel", revenue: 189400, trend: 8.5 },
    { name: "阳朔西街餐厅", type: "restaurant", revenue: 156200, trend: -3.2 },
    { name: "象山购物中心", type: "shopping", revenue: 134500, trend: 5.1 },
    { name: "漓江风景区", type: "scenic", revenue: 123400, trend: 15.8 },
  ],
  rating: [
    { name: "桂林景区", type: "scenic", rating: 4.8, trend: 0.2 },
    { name: "龙胜酒店", type: "hotel", rating: 4.7, trend: 0.1 },
    { name: "阳朔西街餐厅", type: "restaurant", rating: 4.6, trend: -0.1 },
    { name: "象山购物中心", type: "shopping", rating: 4.5, trend: 0.3 },
    { name: "漓江风景区", type: "scenic", rating: 4.4, trend: 0.2 },
  ],
  orders: [
    { name: "桂林景区", type: "scenic", orders: 2568, trend: 15.3 },
    { name: "龙胜酒店", type: "hotel", orders: 1894, trend: 8.5 },
    { name: "阳朔西街餐厅", type: "restaurant", orders: 1562, trend: -3.2 },
    { name: "象山购物中心", type: "shopping", orders: 1345, trend: 5.1 },
    { name: "漓江风景区", type: "scenic", orders: 1234, trend: 12.8 },
  ],
};

// 计算属性
const getRankingColumn = computed(() => {
  const columnMap = {
    revenue: "revenue",
    rating: "rating",
    orders: "orders",
  };
  return columnMap[rankingType.value];
});

const getRankingLabel = computed(() => {
  const labelMap = {
    revenue: "营收金额",
    rating: "综合评分",
    orders: "订单数量",
  };
  return labelMap[rankingType.value];
});

// 初始化图表
const initCharts = () => {
  // 初始化交易趋势图表
  if (transactionChart.value) {
    const transactionChartInstance = echarts.init(transactionChart.value);
    transactionChartInstance.setOption({
      tooltip: {
        trigger: "axis",
      },
      xAxis: {
        type: "category",
        data: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
      },
      yAxis: {
        type: "value",
      },
      series: [
        {
          data: [820, 932, 901, 934, 1290, 1330, 1320],
          type: "line",
          smooth: true,
        },
      ],
    });
  }

  // 初始化商家分布图表
  if (distributionChart.value) {
    const distributionChartInstance = echarts.init(distributionChart.value);
    distributionChartInstance.setOption({
      tooltip: {
        trigger: "item",
      },
      series: [
        {
          type: "pie",
          radius: "50%",
          data: [
            { value: 1048, name: "景点" },
            { value: 735, name: "酒店" },
            { value: 580, name: "餐饮" },
            { value: 484, name: "购物" },
          ],
        },
      ],
    });
  }

  // 初始化评分分布图表
  if (ratingChart.value) {
    const ratingChartInstance = echarts.init(ratingChart.value);
    ratingChartInstance.setOption({
      tooltip: {
        trigger: "axis",
      },
      xAxis: {
        type: "category",
        data: ["1分", "2分", "3分", "4分", "5分"],
      },
      yAxis: {
        type: "value",
      },
      series: [
        {
          data: [10, 52, 200, 334, 390],
          type: "bar",
        },
      ],
    });
  }

  // 初始化投诉分析图表
  if (complaintChart.value) {
    complaintChartInstance.value = echarts.init(complaintChart.value);
    renderComplaintTypeChart();
  }

  // 监听窗口大小变化
  window.addEventListener("resize", () => {
    if (transactionChart.value) {
      echarts.getInstanceByDom(transactionChart.value)?.resize();
    }
    if (distributionChart.value) {
      echarts.getInstanceByDom(distributionChart.value)?.resize();
    }
    if (ratingChart.value) {
      echarts.getInstanceByDom(ratingChart.value)?.resize();
    }
    if (complaintChartInstance.value) {
      complaintChartInstance.value.resize();
    }
  });
};

// 获取数据方法
const fetchData = async () => {
  loading.value = true;
  try {
    // 设置默认日期范围，如果未选择
    if (!dateRange.value || dateRange.value.length === 0) {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30); // 默认最近30天
      dateRange.value = [start, end];
    }

    // 格式化日期
    const startDate = dateRange.value[0] ? formatDate(dateRange.value[0]) : '';
    const endDate = dateRange.value[1] ? formatDate(dateRange.value[1]) : '';

    // 调用获取数据API
    const res = await service.get("/admin/merchants/analysis", {
      params: {
        startDate,
        endDate,
        transactionChartType: transactionChartType.value,
        distributionChartType: distributionChartType.value,
        ratingDimension: ratingDimension.value,
        complaintChartType: complaintChartType.value,
        rankingType: rankingType.value
      }
    });

    // 更新数据和图表
    if (res && res.code === 200) {
      // 更新数据概览
      if (res.data.overview && res.data.overview.length > 0) {
        overviewData.value = res.data.overview;
      } else {
        overviewData.value = testOverviewData;
      }

      // 更新排行榜数据
      if (res.data.ranking && res.data.ranking.length > 0) {
        rankingList.value = res.data.ranking;
      } else {
        rankingList.value = testRankingData[rankingType.value];
      }

      // 更新交易趋势图表
      if (res.data.transactionChart && transactionChart.value) {
        const chartInstance = echarts.getInstanceByDom(transactionChart.value);
        chartInstance.setOption({
          xAxis: {
            data: res.data.transactionChart.xAxis || []
          },
          series: [{
            data: res.data.transactionChart.data || []
          }]
        });
      }

      // 更新商家分布图表
      if (res.data.distributionChart && distributionChart.value) {
        const chartInstance = echarts.getInstanceByDom(distributionChart.value);
        chartInstance.setOption({
          series: [{
            data: res.data.distributionChart.data || []
          }]
        });
      }

      // 更新评分分布图表
      if (res.data.ratingChart && ratingChart.value) {
        const chartInstance = echarts.getInstanceByDom(ratingChart.value);
        chartInstance.setOption({
          xAxis: {
            data: res.data.ratingChart.xAxis || []
          },
          series: [{
            data: res.data.ratingChart.data || []
          }]
        });
      }

      // 更新投诉分析图表
      if (res.data.complaintChart && complaintChartInstance.value) {
        if (complaintChartType.value === "type") {
          complaintChartInstance.value.setOption({
            series: [{
              data: res.data.complaintChart.data || []
            }]
          });
        } else {
          complaintChartInstance.value.setOption({
            xAxis: {
              data: res.data.complaintChart.xAxis || []
            },
            series: res.data.complaintChart.series || []
          });
        }
      }
    } else {
      // 如果API调用失败或没有返回数据，使用测试数据
      overviewData.value = testOverviewData;
      rankingList.value = testRankingData[rankingType.value];
    }
  } catch (error) {
    console.error("获取数据失败：", error);
    ElMessage.error("获取数据失败，使用测试数据");
    
    // 使用测试数据
    overviewData.value = testOverviewData;
    rankingList.value = testRankingData[rankingType.value];
  } finally {
    loading.value = false;
  }
};

// 日期变化处理
const handleDateChange = () => {
  fetchData();
};

// 格式化日期为YYYY-MM-DD
const formatDate = (date) => {
  if (!date) return '';
  const d = new Date(date);
  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, '0');
  const day = String(d.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

// 导出报表
const handleExport = () => {
  // 生成Excel文件
  const wb = XLSX.utils.book_new();
  
  // 导出数据概览
  const overviewWs = XLSX.utils.json_to_sheet(
    overviewData.value.map(item => ({
      '指标': item.label,
      '数值': item.value,
      '同比增长': `${item.trend}%`
    }))
  );
  XLSX.utils.book_append_sheet(wb, overviewWs, '数据概览');
  
  // 导出排行榜
  const rankingWs = XLSX.utils.json_to_sheet(
    rankingList.value.map((item, index) => ({
      '排名': index + 1,
      '商家名称': item.name,
      '商家类型': getMerchantTypeLabel(item.type),
      [getRankingLabel.value]: rankingType.value === 'revenue' ? `¥${item.revenue}` : 
                           rankingType.value === 'rating' ? item.rating : 
                           item.orders,
      '环比增长': `${item.trend}%`
    }))
  );
  XLSX.utils.book_append_sheet(wb, rankingWs, '商家排行');
  
  // 生成文件名
  const startDate = dateRange.value && dateRange.value[0] ? formatDate(dateRange.value[0]) : '';
  const endDate = dateRange.value && dateRange.value[1] ? formatDate(dateRange.value[1]) : '';
  const fileName = `商家运营分析报表_${startDate}_${endDate}.xlsx`;
  
  // 导出文件
  XLSX.writeFile(wb, fileName);
  
  ElMessage.success("报表导出成功");
};

// 获取商家类型标签
const getMerchantTypeTag = (type) => {
  const typeMap = {
    scenic: "success",
    hotel: "primary",
    restaurant: "warning",
    shopping: "info",
  };
  return typeMap[type];
};

// 获取商家类型标签文本
const getMerchantTypeLabel = (type) => {
  const labelMap = {
    scenic: "景点",
    hotel: "酒店",
    restaurant: "餐饮",
    shopping: "购物",
  };
  return labelMap[type];
};

// 监听图表类型变化
watch(
  [
    transactionChartType,
    distributionChartType,
    ratingDimension,
    complaintChartType,
  ],
  () => {
    fetchData();
  },
);

// 监听排行类型变化
watch(rankingType, () => {
  fetchData();
});

// 监听投诉类型变化
watch(complaintChartType, (newType) => {
  if (newType === "type") {
    renderComplaintTypeChart();
  } else {
    renderComplaintTrendChart();
  }
});

// 渲染投诉类型分布图表
const renderComplaintTypeChart = () => {
  const option = {
    title: {
      text: "投诉类型分布",
      left: "center",
    },
    tooltip: {
      trigger: "item",
      formatter: "{a} <br/>{b}: {c} ({d}%)",
    },
    legend: {
      orient: "vertical",
      left: "left",
      data: [
        "商品质量",
        "服务态度",
        "虚假宣传",
        "价格争议",
        "卫生问题",
        "其他",
      ],
    },
    series: [
      {
        name: "投诉类型",
        type: "pie",
        radius: ["40%", "70%"],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: "#fff",
          borderWidth: 2,
        },
        label: {
          show: false,
          position: "center",
        },
        emphasis: {
          label: {
            show: true,
            fontSize: "20",
            fontWeight: "bold",
          },
        },
        labelLine: {
          show: false,
        },
        data: [
          { value: 35, name: "商品质量" },
          { value: 25, name: "服务态度" },
          { value: 15, name: "虚假宣传" },
          { value: 12, name: "价格争议" },
          { value: 8, name: "卫生问题" },
          { value: 5, name: "其他" },
        ],
      },
    ],
  };
  complaintChartInstance.value?.setOption(option);
};

// 渲染投诉趋势图表
const renderComplaintTrendChart = () => {
  const option = {
    title: {
      text: "投诉趋势分析",
      left: "center",
    },
    tooltip: {
      trigger: "axis",
    },
    legend: {
      data: ["总投诉量", "已处理", "处理中", "待处理"],
      bottom: 0,
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "10%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      boundaryGap: false,
      data: ["1月", "2月", "3月", "4月", "5月", "6月"],
    },
    yAxis: {
      type: "value",
    },
    series: [
      {
        name: "总投诉量",
        type: "line",
        stack: "Total",
        data: [120, 132, 101, 134, 90, 230],
        smooth: true,
      },
      {
        name: "已处理",
        type: "line",
        stack: "Total",
        data: [100, 120, 90, 120, 80, 200],
        smooth: true,
      },
      {
        name: "处理中",
        type: "line",
        stack: "Total",
        data: [15, 10, 8, 12, 8, 20],
        smooth: true,
      },
      {
        name: "待处理",
        type: "line",
        stack: "Total",
        data: [5, 2, 3, 2, 2, 10],
        smooth: true,
      },
    ],
  };
  complaintChartInstance.value?.setOption(option);
};

// 页面加载完成后初始化
onMounted(() => {
  initCharts();
  fetchData();
});

// 销毁时清理
onUnmounted(() => {
  complaintChartInstance.value?.dispose();
  window.removeEventListener("resize", () => {
    complaintChartInstance.value?.resize();
  });
});
</script>

<style scoped>
.merchant-analysis {
  padding: 20px;
  height: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-right {
  display: flex;
  gap: 16px;
}

.data-overview {
  margin-bottom: 20px;
}

.overview-card {
  margin-bottom: 15px;
}

.overview-content {
  display: flex;
  align-items: center;
}

.overview-icon {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
}

.overview-icon i {
  font-size: 24px;
  color: #fff;
}

.overview-info {
  flex: 1;
}

.overview-info .label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 4px;
}

.overview-info .value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.overview-info .trend {
  font-size: 12px;
  margin-top: 4px;
}

.overview-info .trend.up {
  color: #67c23a;
}

.overview-info .trend.down {
  color: #f56c6c;
}

.overview-info .trend i {
  margin-left: 4px;
}

.chart-row {
  margin-bottom: 20px;
}

.chart-card {
  margin-bottom: 15px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-container {
  padding: 20px 0;
}

.ranking-card {
  margin-top: 20px;
}

.ranking-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.trend-up {
  color: #67c23a;
}

.trend-down {
  color: #f56c6c;
}

.empty-state {
  padding: 40px 0;
  text-align: center;
}

.empty-text {
  font-size: 16px;
  color: var(--el-text-color-secondary);
  margin-top: 10px;
}

.empty-subtext {
  font-size: 14px;
  color: var(--el-text-color-placeholder);
  margin-top: 5px;
}

.mt-4 {
  margin-top: 16px;
}

/* 添加额外样式与disputes.vue保持一致 */
.form-header {
  margin-bottom: 15px;
}

.form-header .title {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}

.form-footer {
  margin-top: 15px;
  text-align: center;
}

.table-container {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.evidence-image {
  width: 100px;
  height: 100px;
  object-fit: cover;
  margin-right: 10px;
  margin-bottom: 10px;
}

.evidence-files {
  margin-top: 15px;
}
</style>
